/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "growing_buffer.h"

#include <stddef.h>
#include <stdlib.h>

void CreateBuffer(growing_buffer* buffer) {
	buffer->data = malloc(16);
	buffer->size = 0;
	buffer->capacity = 16;
}

void* GrowBuffer(growing_buffer* buffer, int grow_size) {
	buffer->size += grow_size;
	if (buffer->size > buffer->capacity) {
		buffer->capacity = buffer->size + buffer->size / 2 + 16;
		buffer->data = realloc(buffer->data, buffer->capacity);
	}
	return ((char*) buffer->data) + buffer->size - grow_size;
}

void* GetBufferPointer(growing_buffer* buffer, int offset) {
	return ((char*) buffer->data) + offset;
}

void DeleteBuffer(growing_buffer* buffer) {
	free(buffer->data);
	buffer->data = NULL;
	buffer->size = 0;
	buffer->capacity = 0;
}

void* GetBufferEnd(growing_buffer* buffer) {
	return ((char*) buffer->data) + buffer->size;
}
